package com.ce.cetag.tags.select;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.ce.cetag.model.MySelectModel;
import com.ce.cetag.util.MarkupWriterImpl;
import com.ce.cetag.util.StringUtil;


/**
 *
 *  功能描述：
 *
 * <p> 版权所有：中企动力</p>
 * <p> 未经本公司许可，不得以任何方式复制或使用本程序</p>
 * @author ��˧��贺帅彪
 * @create date : 2007-8-7
 */

public class SelectGroup extends BodyTagSupport {

	private static final long serialVersionUID = 8566857848393128051L;

	private String model;

	private String fieldLength;

	private String headId;

	public String getModel() {

		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}

	// ����Ĭ�ϳ��ȵ�ֵ
	public int getFieldLengthNum() {
		if (fieldLength == null) {
			return 20;
		}
		return Integer.parseInt(fieldLength);
	}

	public String getFieldLength() {

		return this.fieldLength;
	}

	public void setFieldLength(String fieldLength) {
		this.fieldLength = fieldLength;
	}

	public String getHeadId() {
		return headId;
	}

	public void setHeadId(String head) {
		this.headId = head;
	}

	private List ids = new ArrayList();

	private List defaultValue = new ArrayList();

	private List defaultStr = new ArrayList();

	private int idCount = 0;

	private int count = 0;

	private final static String data = "_Data";

	private final static String str1 = " = new SelectNode(\"";

	private final static String str2 = "\",\"";

	private final static String str3 = "\");\n";

	private final static String str4 = ".add(";

	private final static String str5 = ");\n";

	private StringBuffer str = new StringBuffer();

	public int addCount() {
		this.idCount++;
		return this.idCount;
	}

	@Override
	public int doStartTag() throws JspException {
		pageContext.setAttribute("head", getHeadId());
		pageContext.setAttribute("defaultValue", defaultValue);
		pageContext.setAttribute("ids", ids);
		return EVAL_BODY_INCLUDE;
	}

	@Override
	public int doAfterBody() throws JspException {
		return super.doAfterBody();
	}

	@Override
	public int doEndTag() throws JspException {

		writeScript();
		cleanupAfterRender();
		return super.doEndTag();
	}

	public String getIds(int i) {
		return (String) ids.get(i);
	}

	private void writeScript() {

		JspWriter out = pageContext.getOut();
		MarkupWriterImpl writer = new MarkupWriterImpl(out);
		writer.begin("script");
		writer.attribute("type", "text/javascript");
		writer.print(getScriptString());

		writer.end();
	}

	public String getScriptString() {

		ids = (List) pageContext.getAttribute("ids");
		defaultValue = (List) pageContext.getAttribute("defaultValue");

		for (int i = 0; i < ids.size(); i++) {

			str.append("var " + ids.get(i) + "_ids = [];\n");
			str.append("var " + ids.get(i) + "_point = null;\n");

			for (int j = i + 1, co = 0; j < ids.size(); j++, co++) {
				str.append(ids.get(i) + "_ids[" + co + "] = \"" + ids.get(j)
						+ "\";\n");
			}
		}

		MySelectModel model = (MySelectModel) pageContext.getRequest()
				.getAttribute(getModel());
		// getHtmlEncode(model);
		String headNode = getHeadId();// String headNode = model.getId();
		str.append("var " + headNode + "= new SelectNode('','') ;\n");
		count = 0;

		initParameters(model, headNode);

		str.append("select_option_add(findId(\"" + this.getIds(0) + "\"),"
				+ headNode + ");\n");

		str.append("function reset_selectgroup" + headNode + "(){\n");
		for (int i = 0; i < defaultStr.size(); i++) {
			// setDefaultValue(1,"bm",bm_Head ,bm_ids);
			str.append("setDefaultValue(" + defaultStr.get(i) + ");\n");
		}
		str.append("}\n");
		str.append("reset_selectgroup" + headNode + "();\n");
		return str.toString();

	}

	@SuppressWarnings("unchecked")
	private void initParameters(MySelectModel model, String parentObj) {

		for (int i = 0; i < model.getSize(); i++) {

			MySelectModel temp = model.get(i);
			escapeHtmlEncode(temp);
			if (temp == null)
				break;
			// ����Ĭ��ֵ
			if (temp.getId().equals(defaultValue.get(count))) {
				String point = getHeadId();
				for (int c = 0; c < count; c++) {
					point += ".point";
				}

				defaultStr.add((i - (Integer)pageContext.getAttribute("haveContent")) + ",\"" + ids.get(count) + "\"," + point + ","
						+ ids.get(count) + "_ids");
			}

			String nodeStr = ids.get(count) + data + i;

			if (!temp.getName().equals("")) {
				str.append(nodeStr
						+ str1
						+ temp.getId()
						+ str2
						+ temp.getName().substring(
								0,
								Math.min(getSubStrLength(temp.getName()),
										getFieldLengthNum())) + str3);

				str.append(parentObj + str4 + nodeStr + str5);
			}
			if (temp.getSize() != 0) {
				count++;
				initParameters(temp, nodeStr);
			}

		}
		count--;
		return;
	}

	private int getSubStrLength(String str) {
		int charVal;
		int byteCount = 0;
		int i = 0;
		for (i = 0; i < str.length(); i++) {
			charVal = (int) str.charAt(i);
			if (charVal > 255) {
				byteCount++;
			}
			byteCount++;
			if (byteCount >= getFieldLengthNum())
				break;
		}
		return i;
	}

	private MySelectModel escapeHtmlEncode(MySelectModel singleModel) {
		singleModel.setId(StringUtil.replaceQuotation(singleModel.getId()));
		singleModel.setName(StringUtil.replaceQuotation(singleModel.getName()));
		return singleModel;
	}

	@SuppressWarnings("unchecked")
	protected void cleanupAfterRender() {
		idCount = 0;
		ids.removeAll(ids);
		defaultValue.removeAll(defaultValue);
		defaultStr.removeAll(defaultStr);
		str.delete(0, str.length());
		pageContext.removeAttribute("defaultValue");
		pageContext.removeAttribute("ids");
		pageContext.removeAttribute("head");
		pageContext.removeAttribute("count");
	}

}
